<template>
    <div class="container">
        <el-row :gutter="20">
            <el-col :span="9">
                <!-- <p>step1: 选择相似性度量方法</p>
                <el-form-item label="" prop="resource">
                    <el-radio-group v-model="form.resource" @change ="handleRadioChange">
                        <el-radio label="从数据库返回最相似样本" value="selectTopK"></el-radio>
                        <el-radio label="样本对相似性度量" value="pairSim"></el-radio>、
                    </el-radio-group>
                </el-form-item> -->

                <p>选择<strong><mark>{{selectNum}}</mark></strong>个样本计算相似性</p>
                <el-form-item label="" prop="transfer">
                    <el-transfer v-model="form.transfer" :data="transferData" :titles="['已上传样本', '选中样本']" filterable/>
                </el-form-item>

                <!-- <p>点击按钮进行相似性计算</p> -->
                <el-button class="step-btn" type="primary"  @click="similarityMeasure">样本对相似性度量</el-button>
            </el-col>

            <el-col :span="15">
                <div class="step-div" v-if = "drawer">
                <el-collapse v-model="activeName" accordion>
                    <el-collapse-item :title="dynamicTitle" name="1">
                        <p>相似值:
                            <countup class="countup" :end="simScore" :options="options" />
                        </p>
                        <el-space wrap>
                            <el-card style="width: 250px">
                                <template #header>
                                    <div class="card-header">
                                        <span>基本信息对比</span>
                                    </div>
                                </template>
                                <!-- <p v-for="o in 4" :key="o" class="text item">{{ 'List item ' + o }}</p> -->
                                <p>家族对比：{{famLabel1 }} : {{famLabel2 }}</p>
                                <p>图节点: {{funcSize1}}:{{funcSize2 }}</p>
                                <p>图边: {{ edgeSize1 }}:{{ edgeSize2 }}</p>
                                <p>重复函数 : {{reuseFunction }}个</p>

                            </el-card>
                            <el-card style="width: 250px">
                                <template #header>
                                    <div class="card-header">
                                        <span>灰度图：</span>
                                    </div>
                                </template> 
                                <p>
                                    <img :src="greyImage1"
                                        style="width: 45%" />
                                    <el-divider direction="vertical" />
                                    <img :src="greyImage2"
                                        style="width: 45%" />
                                </p>
                            </el-card>
                        </el-space>

                    </el-collapse-item>
                    <!-- <el-collapse-item title="样本a vs 样本c" name="2">
                        <p>相似值:
                            <countup class="countup" :end="0.78" :options="options" />
                        </p>
                        <el-space wrap>
                            <el-card style="width: 250px">
                                <template #header>
                                    <div class="card-header">
                                        <span>基本信息</span>
                                    </div>
                                </template>
                                <p v-for="o in 4" :key="o" class="text item">{{ 'List item ' + o }}</p>
                            </el-card>
                            <el-card style="width: 500px">
                                <template #header>
                                    <div class="card-header">
                                        <span>灰度图对比</span>
                                    </div>
                                </template>
                                <img src="../../assets/img/sample1.png" style="width: 30%" />
                                <el-divider direction="vertical" />
                                <img src="../../assets/img/sample2.png" style="width: 30%" />
                            </el-card>
                        </el-space>

                    </el-collapse-item> -->
                </el-collapse>
        </div>
            </el-col>

        </el-row>

    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, compile } from 'vue';
import axios from 'axios';
import { ElStep } from 'element-plus';

const drawer = ref(false)
const selectNum = ref(2)
const transferData = ref([])
const simScore = ref(1)
const dynamicTitle = ref("样本a vs 样本b")
const greyImage1 = ref("")
const greyImage2 = ref("")
const famLabel1 = ref("")
const famLabel2 = ref("")
const reuseFunction = ref(0)
const funcSize1 = ref(0)
const funcSize2 = ref(0)
const edgeSize1 = ref(0)
const edgeSize2 = ref(0)

const similarityMeasure = async () => {
    try {
        let sampleId1
        let sampleId2
        let size  = form.transfer.length;
        if(size == 2){
            console.log("-------------****************")
            console.log(form.transfer)
            console.log(form.transfer.length)
            sampleId1 = transferData.value[form.transfer[0]-1].label
            sampleId2 = transferData.value[form.transfer[1]-1].label 
            const limitSize = 30
            const truncatedSampleId1 = sampleId1.length >  limitSize ? sampleId1.substring(0, limitSize) + '...' : sampleId1;
            const truncatedSampleId2 = sampleId2.length > limitSize ? sampleId2.substring(0, limitSize) + '...' : sampleId2;
            dynamicTitle.value= truncatedSampleId1 +" vs "+truncatedSampleId2
            drawer.value = true
            let userId = 1234
            const response = await axios.post('http://127.0.0.1:5000/calculateSamplePairSim', { userId,sampleId1,sampleId2 });  // 请求后端数据
            simScore.value = response["data"]["simScore"]
            famLabel1.value = response["data"]["famLabel1"]
            famLabel2.value = response["data"]["famLabel2"]
            reuseFunction.value = response["data"]["reuseFunction"]
            funcSize1.value = response["data"]["sampleX"]["funcSize"]
            edgeSize1.value = response["data"]["sampleX"]["edgeSize"]
            funcSize2.value = response["data"]["sampleY"]["funcSize"]
            edgeSize2.value = response["data"]["sampleY"]["edgeSize"]

            axios.post('http://127.0.0.1:5000/queryGreyImage', { tarId:sampleId1 }, { responseType: 'blob' })
            .then(response => {
                // 创建一个图片的URL对象，赋值给imageSrc
                greyImage1.value = URL.createObjectURL(response.data);
            })
            .catch(error => {
                console.error('Error fetching image:', error);
            });

            axios.post('http://127.0.0.1:5000/queryGreyImage', { tarId:sampleId2 }, { responseType: 'blob' })
            .then(response => {
                // 创建一个图片的URL对象，赋值给imageSrc
                greyImage2.value = URL.createObjectURL(response.data);
            })
            .catch(error => {
                console.error('Error fetching image:', error);
            });
        }
        else{
            alert("样本数量选择错误")
        }
    } catch (error) {
        console.error('获取数据失败:', error);
    }
};

const form = reactive({
    name: '',
    region: '',
    date: '',
    time: '',
    delivery: true,
    type: ['小明'],
    resource: '小红',
    desc: '',
    options: [],
    color: '',
    num: 1,
    rate: 0,
    transfer: [],

});

const options = {
    startVal: 0,
    decimalPlaces: 2,
    duration: 5,
    useGrouping: false,
    // prefix: '$',
    separator: ',',
    decimal: '.',
    suffix: '',
}

const activeName = ref('1')

const fetchTableData = async () => {
    try {
        let userId = 1234;
        const response = await axios.post('http://127.0.0.1:5000/querySampleInfoListByUser', { userId });  // 请求后端数据
        transferData.value = []
        var res = []
        for(let ind in response["data"]){
            var tempData = response["data"][ind]
            var dic = new Array()
            console.log(tempData)
            dic["key"] =  tempData[0]
            dic["label"] =  tempData[5]
            transferData.value.push(dic);
        }
    } catch (error) {
        console.error('获取数据失败:', error);
    }
};

const handleRadioChange = (value) => {
    if (value === "selectTopK") {
        selectNum.value = 1;  
    } else if (value === "pairSim") {
        selectNum.value = 2;  
    }
}
// 组件挂载时获取数据
onMounted(() => {
  fetchTableData()
})

</script>

<style scoped>
.step-div {
    max-width: 60%;
    margin: 0 auto;
}

.logo{
    width: 250px;
}
.step-div p {
    margin-bottom: 20px;
    color: #787878;
}

.step-btn {
    display: block;
    width: 100%;
    margin: 20px 0;
}

.step-style {
    max-width: 800px;
    margin: 40px auto;
}
</style>